﻿# 群友分享的。署名为：匿名

# 配置参数
$failPort = 3389
$firewallRuleName = "Blocked RDP IPs"
$maxFailedAttempts = 3

# 获取远程桌面连接失败的IP地址
$failedConnections = Get-EventLog -LogName Security -InstanceId 4625 |
    Where-Object { $_.Message -like "*$failPort*" } |
    ForEach-Object { $_.ReplacementStrings[0] }

# 添加IP地址到防火墙规则
$firewallRule = New-Object -ComObject hnetcfg.fwpolicy2
$firewallRules = $firewallRule.Rules

foreach ($ip in $failedConnections)
{
    # 检查是否已存在相同名称的防火墙规则
    $existingRule = $firewallRules | Where-Object { $_.Name -eq $firewallRuleName -and $_.RemoteAddresses -contains $ip }

    # 获取指定IP的失败连接次数
    $failedCount = Get-EventLog -LogName Security -InstanceId 4625 |
        Where-Object { $_.Message -like "*$failPort*" -and $_.ReplacementStrings[0] -eq $ip } |
        Measure-Object |

        if ($failedCount.Count -ge $maxFailedAttempts -and !$existingRule -and $ip) {
            # 创建新的防火墙规则并将IP地址添加到允许列表中
            $newRule = New-Object -ComObject HNetCfg.FWRule
            $newRule.Name = $firewallRuleName
            $newRule.Description = "Block RDP from $ip"
            $newRule.RemoteAddresses = $ip
            $newRule.Enabled = $true
            $newRule.Action = 1      # 1 表示阻止连接
            $newRule.Direction = 1   # 1 表示入站连接

            $firewallRules.Add($newRule)
        }
}
